import {Injectable} from "@nestjs/common";
import {InjectModel} from "@nestjs/mongoose";
import {Model} from "mongoose";
import {Action, UserActionDocument} from "./userAction.schema";
import {UserAction} from "../../../common/interfaces/userAction";

interface Config {
    [key: string]: any
}

@Injectable()
export class UserActionService {
    constructor(
        @InjectModel("user_action_book") private readonly userActionModel: Model<UserActionDocument>
    ) {
    }

    async insert(userAction: UserAction): Promise<Action> {
        const createUserAction = new this.userActionModel(userAction)
        return await createUserAction.save()
    }

    async update(where: Config, updateActionDto: Config) {
        where = this.filter(where)
        return this.userActionModel.updateOne(where, updateActionDto);

    }

    async find(where: Config) {
        where = this.filter(where)
        return await this.userActionModel.find(where).exec()
    }

    /**
     * @Description: 倒序查找
     * @author zhaojiuyi
     * @date 2023/5/5
     */
    async findSort(where: Config, size?: number) {
        where = this.filter(where)
        return await this.userActionModel.find(where).sort({_id: -1}).limit(size ? size : 20).exec()
    }

    /* 将传递的条件对象进行处理 */
    private filter(where: Config) {
        Object.keys(where).forEach(item => {
            if (!where[item]) {
                console.warn(`键 ${item} 必须指定具体值`)
                delete where[item]
            }
        })
        return where

    }
}
